package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.order.StockBillMaterialDto;
import com.authine.cloudpivot.ext.utils.BoResultFormat;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.common.json.JsonUtils;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

/**
 * @ClassName VmiConsumStatisticService
 * @Description: 寄售消耗统计自定义服务
 * @Author cjj
 * @Date 2021/4/20
 * @Version V1.0
 **/
@Path("VmiConsumStatisticService")
@Slf4j
public class VmiConsumStatisticService extends ApplicationBaseService {
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);

    /**
     * 进领存统计列表
     *
     * @return
     */
    @Path("billStatisticList")
    @POST
    @Operation(summary = "寄售消耗统计-进领存统计列表", tags = CUSTOM_SERVICE)
    public SingleResponse<BOList> billStatisticList() {
        String append = " ";
        //TODO 数据权限区分
//        if(sessionUser.isVendor()){
//            append = "  where vendor_id= " + organizationId;
//        }
//        if(sessionUser.isCustomer()){
//            append = "  where customer_id= " + organizationId;
//        }
        String tableName = getTableName(ModelConst.T_STOCK_BILL_MATERIAL);
        /*String listSql = "select CONCAT_WS(' ',a.brand,a.name,model,spec) as name,unit,a.time as createdTime, sum_receive as receive_num,sum_use as use_num,sum_return as return_num,vName as vendor_name,b.name as customer_name from( " +
                "select a.*,b.name vName from(\n" +
                "select brand,name,model,spec,unit,customer_id,vendor_id,time,sum(receive_num) as sum_receive,sum(use_num) as sum_use,sum(return_num) as sum_return from( " +
                "select customer_id,vendor_id,goods_id,type,brand,name,model,spec,unit,num,receive_num,use_num,return_num, DATE_FORMAT(createdTime,'%Y-%m-%d') as time FROM " + tableName +
                "" + append +
                " )a\n" +
                "group by brand,name,model,spec,unit,customer_id,vendor_id,goods_id,time)a " +
                "inner join " + AppConst.APP_COMMONSERVICE + ".h_org_user_base b on a.vendor_id =b.id)a  " +
                "inner join " + AppConst.APP_COMMONSERVICE + ".h_org_user_base b on a.customer_id =b.id order by time desc";*/
        String listSql = "  SELECT CONCAT_WS( ' ', a.brand, a.name, model, spec ) AS name,unit,customer_id,vendor_id,time AS createdTime, " +
                " sum( receive_num ) AS receive_num,sum( use_num ) AS use_num,sum( return_num ) AS return_num " +
                " FROM(SELECT customer_id,vendor_id,goods_id,type,brand,NAME,model,spec,unit,num,receive_num,use_num," +
                " return_num,DATE_FORMAT( createdTime, '%Y-%m-%d' ) AS time " +
                " FROM " + tableName + append + ") a " +
                " GROUP BY brand,NAME,model,spec,unit,customer_id,vendor_id,goods_id,time " +
                " ORDER BY time DESC";
        log.info("------------------------金税编码管理为空列表 billStatisticList Sql：{}------------------------", listSql);
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql, new HashMap<>());
        //构建结果集
//        BoResultFormat.resultFormat(resultList, ModelConst.T_STOCK_BILL_MATERIAL);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(resultList.size());
        bOList.setSchemaCode(ModelConst.T_STOCK_BILL_MATERIAL);
        return SingleResponse.of(bOList);
    }

    /**
     * 消耗待结算明细列表
     *
     * @param dto
     * @return
     */
    @Path("consumStatisticList")
    @POST
    @Operation(summary = "寄售消耗统计-消耗待结算明细列表分页查询", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public SingleResponse<BOList> consumStatisticList(@Parameter StockBillMaterialDto dto) {
        log.info("------------------------寄售消耗统计-消耗待结算明细列表分页查询 consumStatisticList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        String tableName = getTableName(ModelConst.T_STOCK_BILL_MATERIAL);
        String stockTableName = getTableName(ModelConst.T_STOCK_BILL);
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select bm.* from " + tableName + " bm" +
                " inner join " + stockTableName + " b on bm.stock_bill_id = b.id " +
                " where bm.deleted='0' and b.deleted='0' and bm.type in ('USE','RETURN','CHECK_LOSS') and bm.settlement = '1' and b.stock_bill_status ='WOKING' ");
        countSql.append("select count(*) from " + tableName + " bm " +
                " inner join " + stockTableName + " b on bm.stock_bill_id = b.id " +
                " where bm.deleted='0' and b.deleted='0' and bm.type in ('USE','RETURN','CHECK_LOSS') and bm.settlement = '1' and b.stock_bill_status ='WOKING' ");
        //拼接参数
        if (StringUtils.isNotBlank(dto.getId())) {
            List<String> ids = StringUtils.stringToListString(dto.getId(), ";");
            whereSql.append(" and bm.id in (:id) ");
            parameter.put("id", ids);
        }
        if (StringUtils.isNotBlank(dto.getVendorName())) {
            whereSql.append(" and bm.vendor_name like :vendor_name ");
            parameter.put("vendor_name", "%" + dto.getVendorName() + "%");
        }
        if (StringUtils.isNotBlank(dto.getCustomerName())) {
            whereSql.append(" and bm.customer_name like :customer_name ");
            parameter.put("customer_name", "%" + dto.getCustomerName() + "%");
        }
        if (StringUtils.isNotBlank(dto.getBrand())) {
            whereSql.append(" and bm.brand like :brand ");
            parameter.put("brand", "%" + dto.getBrand() + "%");
        }
        if (StringUtils.isNotBlank(dto.getName())) {
            whereSql.append(" and bm.name like :name ");
            parameter.put("name", "%" + dto.getName() + "%");
        }
        if (StringUtils.isNotBlank(dto.getModel())) {
            whereSql.append(" and bm.model like :model ");
            parameter.put("model", "%" + dto.getModel() + "%");
        }
        if (StringUtils.isNotBlank(dto.getSpec())) {
            whereSql.append(" and bm.spec like :spec ");
            parameter.put("spec", "%" + dto.getSpec() + "%");
        }
        if (StringUtils.isNotBlank(dto.getStartTime()) && StringUtils.isNotBlank(dto.getEndTime())) {
            whereSql.append(" and bm.createdTime between :startTime and :endTime ");
            parameter.put("startTime", dto.getStartTime());
            parameter.put("endTime", dto.getEndTime());
        }
        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by bm.createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------消耗待结算明细列表 consumStatisticList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        log.info("------------------------消耗待结算明细列表 consumStatisticList whereSql：{}------------------------parameter：{}", whereSql, listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        log.info("------------------------消耗待结算明细列表 consumStatisticList Result：{}---------total：{}---------------", JSONObject.toJSONString(resultList), count);
        //构建结果集
        BoResultFormat.resultFormat(resultList, ModelConst.T_STOCK_BILL_MATERIAL);
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode(ModelConst.T_STOCK_BILL_MATERIAL);
        return SingleResponse.of(bOList);
    }

    /**
     * 寄售消耗统计-生成订单页
     *
     * @param dto
     * @return
     */
    @Path("creatOrder")
    @POST
    @Operation(summary = "寄售消耗统计-生成订单页", tags = CUSTOM_SERVICE, description = "ids必填")
    public SingleResponse<BO> creatOrder(@Parameter StockBillMaterialDto dto) {
        if (CollectionUtils.isEmpty(dto.getIds())) {
            return SingleResponse.buildFailure("-1", "库存相关单据物料ID集合必填");
        }
        Map<String, Object> customerOrder = buildOrder(dto.getIds());
        //构建结果集
        BO bo = new BO();
        bo.setData(customerOrder);
        bo.setSchemaCode(ModelConst.T_ORDER_CUSTOMER);
        return SingleResponse.of(bo);
    }
}
